/**
 * 
 */
package com.trungkent.smsbackup;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import org.simpleframework.xml.core.Persister;

import com.trungkent.smsbackup.adapter.SMSAdapter;
import com.trungkent.smsbackup.model.Person;
import com.trungkent.smsbackup.model.PersonList;
import com.trungkent.smsbackup.model.SMS;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @author TrungKent
 * 
 */
public class SMSActivity extends Activity {

	private GetAllSMSFromDevice mGetAllSMSFromDevice;
	private GetAllConversationSMS mGetAllConversationSMS;
	private RetreiveContactName mRetreiveContactName;
	private StartBackupSMS mStartBackupSMS;
	
	private WaitHandler mWaitHandler;

	private SMS mSMS;

	private Uri allMessage;

	private ContentResolver mContentResolver;

	private static final int COMPLETED = 1;

	private int counter;
	private int totalConversation;

	private DateFormat mDateFormat;
	private Calendar mCalendar;

	private ListView mConversationList;

	private SMSAdapter mSMSAdapter;

	private ArrayList<Person> mPersonList;

	private Person mPerson;

	private HashMap<String, String> mapName;

	private CheckBox mCheckBoxAll;

	private Button btnStartBackup;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sms);

		allMessage = Uri.parse("content://sms");

		mapName = new HashMap<String, String>();

		mGetAllConversationSMS = new GetAllConversationSMS();
		mGetAllConversationSMS.execute();

		mWaitHandler = new WaitHandler();

		mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		mCalendar = Calendar.getInstance();

		mConversationList = (ListView) findViewById(R.id.ltvConversations);

		mCheckBoxAll = (CheckBox) findViewById(R.id.cbSelect);
		mCheckBoxAll
				.setOnCheckedChangeListener(OnCheckBoxAllCheckedChangeListener);

		btnStartBackup = (Button) findViewById(R.id.btnStartBackup);
		btnStartBackup.setOnClickListener(onBtnBackupClickListener);

		mPersonList = new ArrayList<Person>();
	}

	private class GetAllConversationSMS extends AsyncTask<Void, Void, Void> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected Void doInBackground(Void... params) {
			mContentResolver = getContentResolver();
			String[] projection = { "thread_id" };

			Cursor mCursor = mContentResolver.query(allMessage, projection,
					null, null, null);

			while (mCursor.moveToNext()) {
				if (!mapName.containsKey(mCursor.getString(0))) {
					mapName.put(mCursor.getString(0), null);
					mGetAllSMSFromDevice = new GetAllSMSFromDevice();
					mGetAllSMSFromDevice.execute(mCursor.getString(0));
					totalConversation++;
				}
			}
			mCursor.close();
			return null;
		}
	}

	private class GetAllSMSFromDevice extends AsyncTask<String, Void, Void> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected Void doInBackground(String... index) {
			ArrayList<SMS> mSMSList = new ArrayList<SMS>();
			String[] projection = { "_id", "thread_id", "address", "person",
					"date", "body", "type" };

			mContentResolver = getContentResolver();

			Cursor mCursor = mContentResolver.query(allMessage, projection,
					"thread_id = '" + index[0] + "'", null, null);
			while (mCursor.moveToNext()) {
				mSMS = new SMS();
				mSMS.thread_id = mCursor.getString(mCursor
						.getColumnIndex(projection[1]));
				mSMS.address = mCursor.getString(mCursor
						.getColumnIndex(projection[2]));
				mSMS.person = mCursor.getString(mCursor
						.getColumnIndex(projection[3]));
				mSMS.date = mCursor.getString(mCursor
						.getColumnIndex(projection[4]));
				mSMS.body = mCursor.getString(mCursor
						.getColumnIndex(projection[5]));
				mSMS.type = mCursor.getString(mCursor
						.getColumnIndex(projection[6]));
				mSMSList.add(mSMS);
			}

			mCursor.close();

			mPerson = new Person();
			mPerson.smsList = mSMSList;

			mPersonList.add(mPerson);

			mRetreiveContactName = new RetreiveContactName();
			mRetreiveContactName.execute(mPersonList.size());
			return null;
		}
	}

	private class RetreiveContactName extends AsyncTask<Integer, Void, Void> {

		private String displayName;
		private String photoUri;
		private String address;

		@Override
		protected Void doInBackground(Integer... index) {
			address = mPersonList.get(index[0] - 1).smsList.get(0).address;

			Uri personUri = Uri.withAppendedPath(
					ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address);
			Cursor mCursor = getContentResolver().query(
					personUri,
					new String[] { PhoneLookup.DISPLAY_NAME,
							PhoneLookup.PHOTO_URI }, null, null, null);

			if (mCursor.moveToFirst()) {
				int nameIdx = mCursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
				displayName = mCursor.getString(nameIdx);

				int photoId = mCursor.getColumnIndex(PhoneLookup.PHOTO_URI);
				this.photoUri = mCursor.getString(photoId);

				mPersonList.get(index[0] - 1).name = displayName;
				mPersonList.get(index[0] - 1).photoUri = this.photoUri;

			}
			mPersonList.get(index[0] - 1).address = address;

			mCursor.close();
			mWaitHandler.sendEmptyMessage(COMPLETED);

			return null;
		}

	}

	private class WaitHandler extends Handler {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.Handler#handleMessage(android.os.Message)
		 */
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case COMPLETED:
				counter++;
				if (counter == totalConversation) {
					mSMSAdapter = new SMSAdapter(SMSActivity.this, mPersonList);

					mConversationList.setAdapter(mSMSAdapter);
					mConversationList
							.setOnItemClickListener(onItemClickListener);
				}

				break;
			default:
				super.handleMessage(msg);
			}
		}
	}

	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View child,
				int position, long id) {

			if (mPersonList.get(position).isCheck) {
				mPersonList.get(position).isCheck = false;
			} else {
				mPersonList.get(position).isCheck = true;
			}

			mSMSAdapter.notifyDataSetChanged();

			for (Person item : mPersonList) {

				if (item.isCheck == false) {
					mCheckBoxAll.setChecked(false);
					mCheckBoxAll.requestLayout();
					break;
				} else {
					mCheckBoxAll.setChecked(true);
					mCheckBoxAll.requestLayout();
					break;
				}
			}
		}
	};

	private OnCheckedChangeListener OnCheckBoxAllCheckedChangeListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			for (Person item : mPersonList) {
				item.isCheck = isChecked;
			}
			mSMSAdapter.notifyDataSetChanged();
		}
	};

	private OnClickListener onBtnBackupClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

		}
	};

	private class StartBackupSMS extends AsyncTask<Void, Void, Void> {
		private ProgressDialog mProgressDialog;
		
		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog = new ProgressDialog(SMSActivity.this);
			mProgressDialog.setTitle(R.string.app_name);
			mProgressDialog.setMessage("Backing up. Please wait...");
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			PersonList person = new PersonList();
			person.person = new ArrayList<Person>();

			for (Person item : mPersonList) {
				if (item.isCheck == true) {
					person.person.add(item);
				}
			}

			Persister mPersister = new Persister();
			File sdcardFile = new File(Environment
					.getExternalStorageDirectory().getPath()
					+ "/SMSCloudBackup/"
					+ mDateFormat.format(mCalendar.getTime()).replace(" ", "-")
							.replace(":", "-") + ".xml");

			try {
				mPersister.write(person, sdcardFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
			
			
			mProgressDialog.dismiss();
		}
	}

}
